package com.thread.sync.sync01;

public class MyObject {
    private static synchronized void method1() {
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //synchronized修饰为同步方法,如果先调用method1,则4秒后才会调用method2
    //如果不用synchronized修饰,则可以直接异步调用,没有影响
    private void method2() {
        System.out.println(Thread.currentThread().getName());
    }

    /**
     * t1线程先获得object的锁,这时,t2线程可以以异步方式调用对象中非synchronized修饰的方法
     * t2线程如果这时要调用对象中同步方法(即synchronized修饰),则需要等待,t1执行完释放锁
     */
    public static void main(String[] args) {
        //创建两个对象
        MyObject myObject = new MyObject();
        MyObject myObject01 = new MyObject();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                myObject.method1();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                myObject01.method1();
            }
        }, "t2");
        t1.start();
        t2.start();
    }

}
